import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import { isLogined } from "../utils/tools";

Vue.use(VueRouter);
// 路由表
const routes = [
  // 首页
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  // 帖子列表
  {
    path: "/post_list",
    name: "PostList",
    component: () => import("../views/PostList.vue"),
  },
  // 登录
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue"),
  },
  // 发布新帖
  {
    path: "/post_new",
    name: "NewPost",
    component: () => import("../views/NewPost.vue"),
    meta: {
      needLogin: true,
    },
  },
  // 帖子详情
  {
    path: "/post",
    name: "Post",
    component: () => import("../views/Post.vue"),
  },
  // 注册
  {
    path: "/register",
    name: "Reg",
    component: () => import("../views/Reg.vue"),
  },
  // 用户中心
  {
    path: "/user",
    name: "User",
    component: () => import("../views/User.vue"),
    meta: {
      needLogin: true,
    },
  },
  // 用户信息修改
  {
    path: "/user_info",
    name: "UserInfo",
    component: () => import("../views/UserInfo.vue"),
    meta: {
      needLogin: true,
    },
  },
  // 修改密码
  {
    path: "/user_pwd",
    name: "UserPwd",
    component: () => import("../views/UserPwd.vue"),
    meta: {
      needLogin: true,
    },
  },
  // 404 要放到最后，因为这回匹配到所有视图页面会造成死循环，路由跳转规则：路由表从上往下进行访问，匹配到正确的就停止不在继续
  {
    path: "*",
    component: () => import("../views/NotFound404.vue"),
  },
];
const router = new VueRouter({
  routes,
});
// 全局守卫
// 路由跳转前会执行这个
router.beforeEach((to, from, next) => {
  // 判断每一次路由跳转是否需要登录
  if (to.meta.needLogin) {
    // 验证token是否存在，如果存在，猪呢革命已经登录，继续执行
    if (isLogined()) {
      console.log("ok");
      next();

      // 没登录，全部跳转到登录页面
    } else {
      console.log("no");
      next({
        name: "Login",
      });
    }
  } else {
    next();
  }
  // 默认先把next放进来，否则会卡死
});

export default router;
